<!-- 用户端聊天室 -->
<template>
	<!-- 防止滚动穿透--page-meta 只能是页面内的第一个节点 -->
	<page-meta :page-style="'overflow:'+(show?'hidden':'visible')"></page-meta>
	<view class="chat">
		<!-- tabBar -->
		<!-- right-text="服务完成" @clickRight="complateService" -->
		<uni-nav-bar title="聊天室" @clickLeft="goHome" left-icon="left"
			backgroundColor="#fff" color="#000" statusBar="true">
		</uni-nav-bar>
		<scroll-view :style="{height: `${windowHeight-inputHeight-50}rpx`}" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" class="scroll-view" @scrolltoupper="scrolltoupper">
			<!-- 聊天主体 -->
			<view @click="seemoreChat" class="chat-record">
				查看更多聊天记录
			</view>
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 系统发的消息 -->
					<view class="system-msg" v-if="item.messageSource == 'system'">
						{{ item.content }}
					</view>
					<!-- 对方发的消息 -->
					<view class="item Ai" v-else-if="item.from == otherId || item.to != otherId">
						<!-- 头像 -->
						<view class="avatar">
							<image v-show="item.avatar" :src="item.avatar" mode="widthFix"></image>
							<image v-show="!item.avatar" src="@/static/socialized-service/nz/kefu/kefu.png"
								mode="widthFix"></image>
						</view>
						<!-- 文字内容 -->
						<view class="content left">
							<mp-html :lazy-load='true' :selectable='true' :content="item.data.content"
								:tag-style='style' v-if="item.data" />
							<mp-html :lazy-load='true' :selectable='true' :content="item.content" :tag-style='style'
								v-else />
							<view class="timeai">
								{{getTime(item.sendTime * 1)}}
							</view>
						</view>
					</view>
					<!-- 自己发的消息 -->
					<view class="item self" v-else>
						<!-- 文字内容 -->
						<view class="content right">
							<!-- {{item.content}} -->
							<mp-html :lazy-load='true' :selectable='true' :content="item.data.content"
								:tag-style='style' v-if="item.data" />
							<mp-html :lazy-load='true' :selectable='true' :content="item.content" :tag-style='style'
								v-else />
							<view class="time">
								{{getTime(item.sendTime * 1)}}
							</view>
						</view>
						<!-- 头像 -->
						<view class="avatar">
							<image v-show="item.avatar" :src="personmesAvg" mode="widthFix"></image>
							<image v-show="!item.avatar" src="@/static/socialized-service/nz/person.png"
								mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
				<view class="uni-textarea">
					<!-- linechange换行后触发 -->
					<textarea v-model.trim()="content" maxlength="300" confirm-type="send" @confirm="sendFirst"
						:show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight" @focus="focus"
						@blur="blur" @input="input" auto-height :disabled="chatOrderStatus != 0"></textarea>
				</view>
				<image src="@/static/socialized-service/nz/add.png" @click="chooseVideoImage" class="add-btn"></image>

				<button @click="sendFirst" :disabled="disable || chatOrderStatus != 0"
					:class="disable || chatOrderStatus != 0?'send-btn send-btn-disable':'send-btn'">发送</button>
			</view>
		</view>
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="warn" cancelText="关闭" confirmText="同意" title="提示" content="与专家聊天断开,是否重新连接？"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="alertDialog1" type="dialog">
			<uni-popup-dialog type="warn" cancelText="关闭" confirmText="同意" title="提示" content="创建会话失败,是否重新创建？"
				@confirm="dialogConfirm1" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import { agrServiceUrl } from '@/config/baseUrl.js'
	import chatApi from '@/api/socialized-servce/specialist-consultation/chart/index.js'

	export default {
		data() {
			return {
				status: '',
				otherId: '', //对方Id
				userId: uni.getStorageSync('userId'), //当前登录者ID
				type: '',
				show: false, //page-meta
				personmesAvg: null,
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				content: "",//发送的消息
				msgList: [],//消息列表
				chatMsg: {
					nowpage: 0,
					total: 0,
					isshowloading: true
				},
				style: {
					// 字符串的形式
					img: 'width:100%;height:100%;',
					video: 'width:200px;height:200px;text-align: center;line-height: 200px;',
				},
				sourceType: ['拍摄', '相册', '拍摄或相册'],
				disable: true, //控制发送按钮
				num: 1,
				endTime: new Date().getTime(),
				chatOrderStatus: ''
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			// this.scrollToBottom();
			// console.log('update');
		},
		// 3.关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
		beforeDestroy() {
			// this.$socketApi.sendMsg({
			// 	type: 6,
			// 	data: {
			// 		to: this.otherId
			// 	}
			// })
			uni.$off('WSMSG')
		},
		computed: {
			// 总高度-tabBar高度
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight - 50)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				// console.log(this.bottomHeight, 'll', this.keyboardHeight);
				return this.bottomHeight + this.keyboardHeight
			}
		},
		onLoad(e) {
			this.chatOrderStatus = e.chatOrderStatus
			this.chatOrderId = e.chatOrderId
			this.type = e.type
			this.otherId = e.otherId //to
			uni.setStorageSync('userCreateNewSessionFlag',true)
			uni.setStorageSync('otherId',e.otherId)
			uni.onKeyboardHeightChange(res => {
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height - 30)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			})
			this.seemoreChat()
		},
		mounted() {
			if (this.$socketApi) {
				// this.createHuihua()
			} else {
				this.$refs.alertDialog.open()
			}
			// TODO:处理收到的消息
			uni.$on('WSMSG', (data) => {
				let res = JSON.parse(data.data)
				if (res.type === 500) {
					if(res.data.content === '会话状态: 已结束, 无法发送消息') {
						this.status = res.data.content
						uni.showToast({
							title: res.data.content,
							icon: 'none'
						})
					} else {
						this.status = ''
					}
					if(this.status === '会话状态: 已结束, 无法发送消息') return
					// if(res.data.content === '当前会话未初始化' ) {
					// 	if(this.num > 0) {
					// 		this.$socketApi.sendMsg({
					// 			type: 5,
					// 			data: {
					// 				to: this.otherId
					// 			}
					// 		})
					// 		this.num--
					// 	}
					// }
					if(res.data.messageType == 'String' && res.data.content == '检测到当前用户创建了新连接, 当前连接断开') {
						uni.showToast({
							title: '此账号已在别处登录,如非本人操作，请检查账号安全！',
							icon: 'none'
						})
						return;
					}
					// 排队
					if(res.data.messageType == 'String' && res.data.content == '会话状态: 等待中, 无法发送消息') {
						uni.showToast({
							title: '等待中...',
							icon: 'loading'
						})
						return;
					}
					// if(res.data.messageType == 'String') {
					// 	this.$refs.alertDialog1.open()
					// }
					return;
				}
				if (res.type === 200) return;
				if (res.type === 2) {
					const param = {
						type: 102,
						data: {
							to: this.otherId,
							messageId: res.data.messageId
						}
					};
					this.$socketApi.sendMsg(param)
				}
				if (res.type === 7 || res.type === 2) {
					let params = {
						type: res.type,
						...res.data
					}
					this.msgList.push(params)
				} else {
					// if(res.data.content.includes('位在排队...')) {
					// 	this.msgList.forEach((el,index)=>{
					// 		if(el.content.includes('位在排队...')) {
					// 			this.msgList.splice(index,1)
					// 		}
					// 	})
					// 	console.log('www');
					// }
					// let params = {
					// 	type: res.type,
					// 	content: res.data.content,
					// 	from: this.otherId,
					// 	to: this.userId
					// }
					// this.msgList.push(params)
				}
				this.scrollToBottom()
			})
			if(this.$socketApi != undefined) {
				let params2 = {
					type: 103,
					data: {
						to: this.otherId,
						endTime: new Date().getTime()
					}
				}
				this.$socketApi.sendMsg(params2)
			}
		},
		onUnload() {
			// uni.offKeyboardHeightChange()
		},
		methods: {
			// 创建会话
			createHuihua() {
				// this.$socketApi.sendMsg({
				// 	type: 5,
				// 	data: {
				// 		to: this.otherId
				// 	}
				// })
			},
			//判断客服聊天有没有断开---------------重连
			async dialogConfirm() {
				uni.setStorageSync('userCreateNewSessionFlag',true)
				uni.$emit('userCreateNewSession',this.otherId)
			},
			dialogConfirm1() {
				// this.$socketApi.sendMsg({
				// 	type: 5,
				// 	data: {
				// 		to: this.otherId
				// 	}
				// })
			},
			dialogClose() {
				if(this.type === 'user') {
					uni.reLaunch({
						url: '/subPage1/socialized-service/specialist-consultation/user-module/expert-list/expert-list'
					})
				} else {
					uni.reLaunch({
						url: '/subPage1/socialized-service/specialist-consultation/user-module/expert-information/expert-information'
					})
				}
			},
			scrolltoupper() {
				this.seemoreChat()
			},
			//点击获取更多的聊天记录
			async seemoreChat() { // 10/9
				if (this.chatMsg.isshowloading) {
					this.chatMsg.nowpage++
					let params = {
						page: this.chatMsg.nowpage,
						size: 5,
						sortList: [],
						condition: {
							to: this.otherId,
							endTime: this.endTime,
							serviceProviderNo: uni.getStorageSync('serviceProviderNo')
						}
					}
					let res = await chatApi.queryHistoryMessage(params)
					if (res.code === 200) {
						if (res.data.length === 0) {
							this.chatMsg.isshowloading = false
						}
						const newList = res.data.reverse()
						this.msgList = newList.concat(this.msgList)
					}
				} else {
					uni.showToast({
						title: '暂无更多消息',
						icon: 'loading'
					})
				}

			},
			// 发送消息
			sendFirst() {
				if (this.content == '' || /^\s*$/.test(this.content)) {
					uni.showToast({
						title: '不能发送空白消息',
						icon: 'none'
					})
				} else {
					const params = {
						type: 101,
						data: {
							chatOrderId: this.chatOrderId,
							to: this.otherId,
							content: this.content,
							messageType: "String"
						}
					}
					this.$socketApi.sendMsg(params)
					this.content = ''
					this.disable = true
				}
			},
			//判断是发送图片还是视频
			chooseVideoImage() {
				if (this.chatOrderStatus != 0) {
					uni.showToast({
						title: '服务已结束',
						icon: 'none'
					})
					return
				}
				uni.showActionSheet({
					title: "请选择发送类型",
					itemList: ['图片', '视频'],
					success: (res) => {
						console.log(res)
						if (res.tapIndex == 0) {
							this.chooseImages()
							console.log('photo');
						} else {
							this.chooseVideo()
							console.log('video');
						}
					}
				})
			},
			chooseImages() {
				// 上传图片
				uni.chooseImage({
					count: 1, //默认9
					// sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						console.log(res);
						let igmFile = res.tempFilePaths;
						uni.uploadFile({
							url: agrServiceUrl + `common/file/upDown/getUploadUrl?moduleType=XG_ORGANIZATION&upDownType=FTP`,
							filePath: igmFile[0],
							name: 'file',
							header: {
								'token': uni.getStorageSync("satoken") || ''
							},
							complete: (res) => {
								if (res.statusCode == 200) {
									const data = JSON.parse(res.data)
									const newconcant =
										`<img src="${agrServiceUrl}${data.data.slice(1)}"></img>`
									console.log(newconcant); //完整的图片地址
									const params = {
										type: 101,
										data: {
											chatOrderId: this.chatOrderId,
											to: this.otherId,
											content: newconcant,
											messageType: "picture"
										}
									}
									this.$socketApi.sendMsg(params)
									this.scrollToBottom()
								}
							}
						})
					},
				});
			},
			//添加视频上传功能
			chooseVideo() {
				// 选择文件
				uni.chooseVideo({
					sourceType: ['album', 'camera'],
					maxDuration: 60,
					camera: 'back',
					success: res => {
						// 选择成功，开始上传文件
						uni.uploadFile({
							url: agrServiceUrl + `common/file/upDown/getUploadUrl?moduleType=XG_ORGANIZATION&upDownType=FTP`,
							filePath: res.tempFilePath, // 要上传的文件路径
							method: "POST",
							name: 'file', // 上传文件对应的 key 值
							complete: (res) => {
								if (res.statusCode == 200) {
									const data = JSON.parse(res.data)
									const videoconcant =
										`<video class="media" height="250" width="300" controls src="${agrServiceUrl}${data.data.slice(1)}"></video>`
									console.log(videoconcant);
									const params = {
										type: 101,
										data: {
											chatOrderId: this.chatOrderId,
											to: this.otherId,
											content: videoconcant,
											messageType: "video"
										}
									}
									this.$socketApi.sendMsg(params)
									this.scrollToBottom()
								}

							}
						});
					}
				});
			},
			// back
			goHome() {
				if (this.type === 'user') {
					uni.redirectTo({
						url: '/subPage1/socialized-service/specialist-consultation/user-module/expert-list/expert-list'
					})
				} else {
					uni.redirectTo({
						url: '/subPage1/socialized-service/specialist-consultation/user-module/expert-information/expert-information'
					})
				}
			},
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			input() {
				if (this.content !== '') {
					this.disable = false
				} else {
					this.disable = true
				}
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = wx.getSystemInfoSync().windowWidth //设备总宽度
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监听聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},
			// 时间戳计算
			getTime(timestamp) {
				// 时间戳转化
				let date = new Date()
				if (timestamp) date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				const Y = date.getFullYear() + '-';
				const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
				const h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
				const m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
				const s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
				return Y + M + D + h + m + s;
			},
			// 服务完成
			// async complateService() {
			// 	// 关闭会话
			// 	this.$socketApi.sendMsg({
			// 		type: 6,
			// 		data: {
			// 			to: this.otherId
			// 		}
			// 	})
			// 	if(this.type === 'user') {
			// 		uni.reLaunch({
			// 			url: '/subPage1/socialized-service/specialist-consultation/user-module/expert-list/expert-list'
			// 		})
			// 	} else {
			// 		uni.reLaunch({
			// 			url: '/subPage1/socialized-service/specialist-consultation/user-module/expert-information/expert-information'
			// 		})
			// 	}
			// }
		}
	}
</script>

<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.send-btn {
		pointer-events: all;
		animation: btnAnim 2s step-end forwards;
	}

	.send-btn:active {
		animation: none
	}

	@keyframes btnAnim {
		from {
			pointer-events: none;
		}

		to {
			pointer-events: all;
		}
	}

	.image-box {
		width: 200rpx;
		height: 100rpx;
	}

	::v-deep .cartImg {
		width: 400rpx;
		height: 250rpx;
		margin: 0rpx;
	}

	/* 聊天消息 */
	.chat {


		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;

					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;

						.timeai {
							width: 600rpx;
							position: absolute;
							top: -40rpx;
							left: 0rpx;
							font-size: 24rpx;
							color: #999;
						}

						.time {
							width: 240rpx;
							position: absolute;
							top: -40rpx;
							right: 0rpx;
							font-size: 24rpx;
							color: #999;
						}
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						// background: $sendBtnbgc;
						border-radius: 50%;
						overflow: hidden;

						image {
							width: 78rpx;
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 177rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;


			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #EDEDED;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				padding-bottom: 70rpx;

				textarea {
					width: 480rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 43rpx;
					padding: 5rpx 8rpx;
				}
			}

			.add-btn {
				width: 75rpx;
				height: 75rpx;
				margin-left: 20rpx;
				border-radius: 50%;
				margin-bottom: 70rpx;
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				background: #0e8bf7;
				border-radius: 8rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}

			.send-btn-disable {
				background-color: #999999;
			}
		}
	}

	.chat-record {
		width: 250rpx;
		height: 34rpx;
		background-color: #999;
		margin: 20rpx auto;
		// font-size: 22rpx;
		color: #444;
		text-align: center;
		line-height: 34rpx;

	}
	
	/deep/.content {
		// min-width: 100rpx!important;
		image {
			width: 200rpx!important;
		}
	}
	.system-msg {
		text-align: center;
		color: #9a9a9a;
		margin-bottom: 20rpx;
	}
</style>